#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)

class StockPicking(models.Model):
    _inherit = "stock.picking"
    is_calc_hide_reject_qty = fields.Boolean(
        compute="_compute_is_calc_hide_reject_qty",
        store=False 
    )

    def check_quality(self):
        if self.check_ids.filtered(lambda x:x.quality_state == 'none' and x.point_id == self.env.ref('sb_iqc.iqc_inspection_point')):
            return self.action_open_iqc_quality_check_action()
        return super().check_quality()

    def action_open_iqc_quality_check_action(self):
        #  check_ids = sorted(self.ids)
        action = self.env["ir.actions.actions"]._for_xml_id("sb_iqc.action_quality_check_view_iqc")
        action['context'] = self.env.context.copy()
        action['domain'] = [('picking_id','in',self.ids)]
        action['context'].update({
            'search_default_picking_id': self.ids,
            'default_picking_id': self.id,
            'default_team_id': self.check_ids.mapped('point_id.team_id').ids[-1:],
            'search_default_team_id': self.check_ids.mapped('point_id.team_id').ids,
            'search_default_progress': "1"
        })
        return action

    def action_open_quality_check_picking(self):
        if self.picking_type_id.code == 'incoming':
            action_pool = self.env["ir.actions.actions"]
            action = action_pool._for_xml_id("sb_iqc.action_quality_check_view_iqc")
            action['context'] = self.env.context.copy()
            action['domain'] = [('team_id','=',self.env.ref('sb_iqc.quality_alert_iqc_team0').id)]
            action['context'].update({
                'search_default_picking_id': [self.id],
                'default_picking_id': self.id,
                'show_lots_text': self.show_lots_text,
            })
            return action
        else:
            return super(StockPicking, self).action_open_quality_check_picking()

    @api.depends('quality_check_todo', 'check_ids')
    def _compute_is_calc_hide_reject_qty(self):
        for record in self.sudo():
            record.is_calc_hide_reject_qty  = record.check_ids  

    def button_validate(self):
        try:
            res = super().button_validate()
        except Exception as error:
            raise error
        else:
            if not self.check_ids.filtered(lambda x:x.point_id == self.env.ref('sb_iqc.iqc_inspection_point')):
                return res
            if type(res) == dict and res.get('res_model','') in ('quality.check.wizard','stock.backorder.confirmation'):
                no_check_rows = self.check_ids.filtered(lambda x:x.quality_state == 'none')
                if no_check_rows:
                    raise ValidationError(_('find iqc quality check, please to check product:{product}').format(product= '/'.join(no_check_rows.mapped('product_id.name'))))
            if type(res) == dict and res.get('res_model','') == 'stock.backorder.confirmation':
                return res
            if not res or not self.env.ref('sb_iqc.iqc_inspection_point'):
                return res
            pass_checks = self.check_ids.filtered(lambda x:x.quality_state == 'pass' \
                                                  and x.point_id == self.env.ref('sb_iqc.iqc_inspection_point'))
            for p_row in pass_checks[-1:]:
                try:
                    p_row.create_iqc_quality_to_stock()
                except Exception as error:
                    _logger.error('sb_iqc: create_iqc_quality_to_stock error:{}'.format(error))
        return res

class StockMove(models.Model):
    _inherit = 'stock.move'

    rejected_qty = fields.Float(
        '拒收数量',
        readonly=True,
        digits='Product Unit of Measure',
        help="本次收货中拒收的数量"
    )
    #@api.constrains('product_uom_qty', 'quantity_done', 'rejected_qty')
    #def _check_qty_constraints(self):
    #    """校验需求数 <= 处理数 + 拒收数量"""
    #    for move in self:
    #        if move.product_uom_qty > move.quantity + move.rejected_qty:
    #            raise ValidationError(
    #                f"需求数 ({move.product_uom_qty}) 不能大于处理数 ({move.quantity}) 加拒收数量 ({move.rejected_qty})！"
    #            )
